package com.cosmoplat.xikai.business.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.cosmoplat.xikai.business.config.mes.MesReqHeader;
import com.cosmoplat.xikai.business.config.mes.MesUrl;
import com.cosmoplat.xikai.business.domain.mes.req.*;
import com.cosmoplat.xikai.business.domain.mes.result.*;
import com.cosmoplat.xikai.business.service.MesRequestService;
import com.cosmoplat.xikai.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName MesRequestServiceImpl
 * @Description TODO
 * @Author wdf
 * @Date 2025/1/8
 */
@Slf4j
@Service
public class MesRequestServiceImpl implements MesRequestService {

    @Autowired
    private MesReqHeader mesReqHeader;

    @Autowired
    private MesUrl mesUrl;

    @Override
    public String sendRequest(MesRequest request)  {
        log.info("请求mes：{}", request);
        Map<String, String> headerMap = initHeaderMap();
        String res = callInterfaceByHeader(request.getUrl(), request.getJson(), request.getReqMethod(), request.getContentType(), headerMap, request);
        log.info("[{}]mes返回内容:{}", request.getUuid(), res);
        if (!isJson(res)) {
            log.error(request.getUuid() + " mes返回内容不是json格式, {}", res);
            throw new ServiceException("mes返回内容不是json格式");
        }
        return res;
    }

    @Override
    public MesResult<Void>  materialDistribution(MesMaterialDistributionRequest distribution) {
        MesRequest request = new MesRequest();
        request.setUrl(mesUrl.getMaterialDistribution());
        request.setJson(JSON.toJSONString(distribution));
        String resultStr = sendRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        MesResult<Void> result = jsonObject.toJavaObject(MesResult.class);
        if (result == null) {
            log.error("同步mes数据异常, 返回数据为空：{}", request);
        }
        return result;
    }

    @Override
    public MesResult<Void> alarm(MesLineAlarmRequest alarm) {
        MesRequest request = new MesRequest();
        request.setUrl(mesUrl.getProductLineAlarm());
        request.setJson(JSON.toJSONString(alarm));
        String resultStr = sendRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        MesResult<Void> result = jsonObject.toJavaObject(MesResult.class);
        if (result == null) {
            log.error("同步mes数据异常, 返回数据为空：{}", request);
        }
        return result;
    }

    @Override
    public MesResult<Void> alarmClose(MesAlarmCloseRequest alarmClose) {
        MesRequest request = new MesRequest();
        request.setUrl(mesUrl.getCloseAlarm());
        request.setJson(JSON.toJSONString(alarmClose));
        String resultStr = sendRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        MesResult<Void> result = jsonObject.toJavaObject(MesResult.class);
        if (result == null) {
            log.error("同步mes数据异常, 返回数据为空：{}", request);
        }
        return result;
    }

    @Override
    public MesQrCodeResult scanCodeToMaterialQty(MesQrCodeRequest qrCode) {
        MesRequest request = new MesRequest();
        request.setUrl(mesUrl.getScanCodeToMaterialQty());
        request.setJson(JSON.toJSONString(qrCode));
        String resultStr = sendRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        MesResult<MesQrCodeBusinessResult<MesQrCodeResult>> result = jsonObject.toJavaObject(MesResult.class);
        if (result == null) {
            log.error("同步mes数据异常, 返回数据为空：{}", request);
        }
        if (!result.checkData()) {
            log.error("同步mes数据异常, 数据异常：{}", result);
            throw new ServiceException("同步mes数据异常, 数据异常");
        }
        JSONObject businessResult = JSONObject.from(result.getData());
        if (businessResult != null && CollectionUtils.isNotEmpty(businessResult.getJSONArray("businessdata"))) {
            List<MesQrCodeResult> businessdata = businessResult.getJSONArray("businessdata").toList(MesQrCodeResult.class);
            return businessdata.get(0);
        }
        log.error("同步mes数据异常, 数据为空：{}", resultStr);
        throw new ServiceException("mes返回数据, 解析为空：" + resultStr);
    }

    @Override
    public MesResult finishTask(MesFinishTaskRequest finishTask) {
        MesRequest request = new MesRequest();
        request.setUrl(mesUrl.getFinishTask());
        request.setJson(JSON.toJSONString(finishTask));
        String resultStr = sendRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        MesResult result = jsonObject.toJavaObject(MesResult.class);
        if (result == null) {
            log.error("同步mes数据异常, 返回数据为空：{}", request);
        }
        return result;
    }

    /**
     * 初始化请求头
     *
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @date 15:54 2025/1/8
     **/
    private Map<String, String> initHeaderMap() {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("X-ECC-Current-Tenant", mesReqHeader.getTenant());
        headerMap.put("Accept-Language", mesReqHeader.getLanguage());
        headerMap.put("Authorization", mesReqHeader.getAuthorization());
        headerMap.put("Systemcode", mesReqHeader.getSystemCode());//联系项目组提供
        return headerMap;
    }


    /**
     * mes 例子
     * @date 15:14 2025/1/10
     * @param args
     **/
    public static void main(String[] args) {
        String path = "http://127.0.0.1:5200/api/xkyxmes/xkmesex/v1.0/XDBasicDataService/ppsczx/operate";
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("X-ECC-Current-Tenant", "10000");
        headerMap.put("Accept-Language", "zh-CHS");
        headerMap.put("Authorization", "Bearer c4a965c1-84e4-764e-9108-7fe66c239b54");
        headerMap.put("Systemcode", "xxxxxxxxxxxxxxx");//联系项目组提供
        String data = "{\n" +
                "    \"code\": \"\",\n" +
                "    \"message\": \"\",\n" +
                "    \"data\": {\n" +
                "        \"orgIdName\": \"\",\n" +
                "        \"masterOrgKeyField\": \"\",\n" +
                "        \"calculatePower\": false,\n" +
                "        \"code\": \"\",\n" +
                "        \"name\": \"\",\n" +
                "        \"modifier\": \"\",\n" +
                "        \"creatorId\": 0,\n" +
                "        \"modifierId\": 0,\n" +
                "        \"memo\": \"\",\n" +
                "        \"orgId\": \"\",\n" +
                "        \"modifyTime\": \"\",\n" +
                "        \"deptIdName\": \"\",\n" +
                "        \"deptIdCode\": \"\",\n" +
                "        \"id\": 0,\n" +
                "        \"pubts\": \"\",\n" +
                "        \"workCenterCategoryId\": 0,\n" +
                "        \"workCenterCategoryIdName\": \"\",\n" +
                "        \"operationControlCodeId\": \"\",\n" +
                "        \"operationControlCodeIdName\": \"\",\n" +
                "        \"stopstatus\": false,\n" +
                "        \"timeUnit\": \"\",\n" +
                "        \"coeffExcess\": 0,\n" +
                "        \"createDate\": \"\",\n" +
                "        \"creator\": \"\",\n" +
                "        \"modifyDate\": \"\",\n" +
                "        \"deptId\": \"\",\n" +
                "        \"workTime\": 0,\n" +
                "        \"createTime\": \"\",\n" +
                "        \"isOutsource\": false,\n" +
                "        \"vendorId\": 0,\n" +
                "        \"vendorId_name\": \"\",\n" +
                "        \"workCalendar\": \"\",\n" +
                "        \"workCalendarName\": \"\",\n" +
                "        \"parent\": 0,\n" +
                "        \"parent_name\": \"\",\n" +
                "        \"usedType\": \"\",\n" +
                "        \"powerUnitType\": \"\",\n" +
                "        \"eqpCount\": 0,\n" +
                "        \"eqpUtilization\": 0,\n" +
                "        \"eqpPower\": 0,\n" +
                "        \"outputUnit\": 0,\n" +
                "        \"outputUnitName\": \"\",\n" +
                "        \"standardOutput\": 0,\n" +
                "        \"maxOutput\": 0,\n" +
                "        \"workCenterDefineCharacter\": {\n" +
                "            \"id\": \"\"\n" +
                "        },\n" +
                "        \"workCenterDetailList\": [\n" +
                "            {\n" +
                "                \"rowno\": \"\",\n" +
                "                \"lineNo\": 0,\n" +
                "                \"workTypeId\": 0,\n" +
                "                \"workCenterId\": 0,\n" +
                "                \"memo\": \"\",\n" +
                "                \"id\": 0,\n" +
                "                \"workTypeIdCode\": \"\",\n" +
                "                \"workTypeIdName\": \"\",\n" +
                "                \"quantity\": 0,\n" +
                "                \"quantityUnit\": 0,\n" +
                "                \"quantityUnitPrecision\": 0,\n" +
                "                \"quantityUnitName\": \"\",\n" +
                "                \"workTypeIdActivityClass\": \"\",\n" +
                "                \"workTypeIdUnitName\": \"\",\n" +
                "                \"workCenterDetailDefineCharacter\": {\n" +
                "                    \"id\": \"\"\n" +
                "                }\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "}";
        System.out.println(postInterfaceJsonByHeader(path, data, headerMap));
    }


    public static String postInterfaceJsonByHeader(String path, String data, Map<String, String> headerMap) {
        return callInterfaceByHeader(path, data, "POST", "application/json", headerMap, null);
    }

    /**
     * 请求mes
     *
     * @param path
     * @param data
     * @param requestMethod
     * @param contentType
     * @param headerMap
     * @param request
     * @return java.lang.String
     * @date 16:09 2025/1/8
     **/
    private static String callInterfaceByHeader(String path, String data, String requestMethod, String contentType, Map<String, String> headerMap, MesRequest request) {
        String uuid = "["+request.getUuid() +"]";
        String outStr = "";
        HttpURLConnection conn = null;
        BufferedReader br = null;
        PrintWriter out = null;
        InputStream is = null;
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            //请求方式
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-Length", String.valueOf(data.length()));
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("Content-Type", contentType);
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            for (Map.Entry<String, String> mapEntry : headerMap.entrySet()) {
                conn.setRequestProperty(mapEntry.getKey(), mapEntry.getValue());
            }

            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out2 = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out = new PrintWriter(out2);
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            out.close();
            try {
                is = conn.getInputStream();// 发送http请求
                //构造一个字符流缓存
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            } catch (IOException e) {
                log.error(uuid + "发送请求异常:{}", e);
                is = conn.getErrorStream();
            }

            String str = "";
            StringBuffer stringBuffer = new StringBuffer();
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str).append("\r\n");
            }
            //关闭流
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            outStr = stringBuffer.toString();
        } catch (Throwable e) {
            log.error(uuid + "接口请求", e);
            throw new ServiceException("mes接口请求异常：" + e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(uuid + "流关闭出错", e);
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error(uuid + "流关闭出错", e);
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return outStr;
    }


    public static boolean isJson(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return false;
        }

        try {
            // 尝试将字符串解析为 JSON 对象或数组
            JSON.parse(jsonString);
            return true;
        } catch (JSONException e) {
            // 如果解析失败，返回 false
            return false;
        }
    }

}
